package com.baikeyang.app.controller.api.admin;

import com.baikeyang.common.bean.ResponseResult;
import com.baikeyang.common.constant.ExecuteConstants;
import com.baikeyang.common.model.User;
import com.baikeyang.common.util.JWTUtil;
import com.baikeyang.common.util.TokenUtil;
import com.baikeyang.common.util.shiro.SecurityUtil;
import com.baikeyang.service.user.IUserService;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController(value = "AdminPassportController")
@RequestMapping(value = "api/v1/admin/passport")
public class AdminPassportController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "login", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseResult login(String userName, String password) {
        ResponseResult result = null;
        Map<String, Object> data = new HashMap<String, Object>();
        try{
            User user = userService.getUserByLoginName(userName);
            if(null != user && user.getPassword().equals(SecurityUtil.encryptPassword(password, Constants.MD5))){ // 登录成功
                String iss = "http://www.bkybk.com/api";
                String token = TokenUtil.createJWT(user.getId().toString(), iss, user.getLoginName(), JWTUtil.DAY_TTL);
                data.put("token", token);
                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_20000, data);
            } else { // 登录失败
                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.失败, ExecuteConstants.EXECUTEINFO.失败, ExecuteConstants.EXECUTECODE.CODE_20000, data);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("用户登录时接口发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

}
